package com.wtp.wallpaper.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtp.wallpaper.common.constant.MessageConstant;
import com.wtp.wallpaper.common.exception.CronIllegalException;
import com.wtp.wallpaper.mapper.ScheduledMapper;
import com.wtp.wallpaper.pojo.dto.ScheduledDTO;
import com.wtp.wallpaper.pojo.entity.ScheduledTime;
import com.wtp.wallpaper.service.ScheduledService;
import com.wtp.wallpaper.utils.TaskSchedulerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.support.CronExpression;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

@Service
public class ScheduledServiceImpl extends ServiceImpl<ScheduledMapper, ScheduledTime> implements ScheduledService {

    @Autowired
    private ApplicationContext context;
    @Override
    public void updateState(ScheduledDTO scheduledDTO) {
        update(scheduledDTO);
    }

    @Override
    public void update(ScheduledDTO scheduledDTO) {

        if(scheduledDTO.getCron() != null && !CronExpression.isValidExpression(scheduledDTO.getCron())){
            throw new CronIllegalException(MessageConstant.CRON_ILLEGAL);
        }

        ScheduledTime scheduledTime = BeanUtil.copyProperties(scheduledDTO, ScheduledTime.class);
        if(scheduledDTO.getIsEnable() != null) scheduledTime.setState(scheduledDTO.getIsEnable() ? 1 : 0);
        updateById(scheduledTime);

        Class<?> clazz = null;
        try {
            clazz = Class.forName(scheduledDTO.getId());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        Runnable bean = (Runnable)context.getBean(clazz);
        if(scheduledTime.getState() == 0){
            TaskSchedulerUtil.delete(scheduledDTO.getId());
        }else {
            TaskSchedulerUtil.put(bean, new CronTrigger(scheduledDTO.getCron()), scheduledDTO.getId());
        }

    }
}
